package com.sjb.thread;

import java.sql.Time;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 有点儿意思
 * @Description:
 */
public class TestCountDown {


    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                16, 16, 1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(100),
                r -> {
                    Thread thread = new Thread(r);
                    thread.setName("Worker-");
                    return thread;
                });

        int numberOfTasks = 10;
        CountDownLatch countDownLatch = new CountDownLatch(numberOfTasks);
        for (int i = 0; i < numberOfTasks; i++) {
            threadPoolExecutor.submit(() -> {
                try {
                    // 模拟执行任务
                    String threadName = Thread.currentThread().getName();
                    System.out.println(threadName + "正在执行的任务");
                    Thread.sleep((long) (Math.random() * 1000));

                    // 模拟可能发生的异常
                    if (Math.random() > 0.8) {
                        throw new RuntimeException("任务执行过程中发生异常");
                    }
                    System.out.println("任务执行完成");
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    System.err.println(Thread.currentThread().getName() + "任务被中断");
                } finally {
                    // 确保在任务完成或发生异常时调用 countDown
                    countDownLatch.countDown();
                }
            });
        }

        // 等待所有任务完成
        try {
            System.out.println("主线程等待所有任务完成");
            // 5s 超时
            boolean allTasksCompleted = countDownLatch.await(5, TimeUnit.SECONDS);
            if (allTasksCompleted) {
                System.out.println("所有任务已完成");
            } else {
                System.out.println("等待超时，有任务未完成");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println("主线程等待时被中断");
        } finally {
            // 关闭线程池
            threadPoolExecutor.shutdown();
        }

    }
}
